﻿using ErrorOr;
using Gym.Application.Common.Interfaces;
using Gym.Domain.TrainerAggregate;
using MediatR;

namespace Gym.Application.Gyms.Commands.AddTrainer
{
    public class AddTrainerCommandHandler : IRequestHandler<AddTrainerCommand, ErrorOr<Success>>
    {
        private readonly IGymsRepository _gymsRepository;
        private readonly ISubscriptionsRepository _subscriptionsRepository;
        private readonly ITrainersRepository _trainersRepository;
        
        public AddTrainerCommandHandler(IGymsRepository gymsRepository, ISubscriptionsRepository subscriptionsRepository, ITrainersRepository trainersRepository)
        {
            _gymsRepository = gymsRepository;
            _subscriptionsRepository = subscriptionsRepository;
            _trainersRepository = trainersRepository;
        }

        public async Task<ErrorOr<Success>> Handle(AddTrainerCommand request, CancellationToken cancellationToken)
        {
            var subscription = await _subscriptionsRepository.GetByIdAsync(request.SubscriptionId);
            
            if (subscription is null)
            {
                return Error.NotFound(description:"没有找到订阅信息");
            }

            if (! subscription.HasGym(request.GymId))
            {
                return Error.NotFound(description: "没有找到该健身房信息");
            }

            var gym = await _gymsRepository.GetByIdAsync(request.GymId);
            
            if (gym is null)
            {
                return Error.NotFound(description: "没有找到该健身房信息");
            }

            if(gym.HasTrainer(request.TrainerId))
            {
                return Error.Conflict(description: "健身房已添加该教练");
            }

            Trainer? trainer = await _trainersRepository.GetByIdAsync(request.TrainerId);
            if (trainer is null)
            {
                return Error.NotFound(description: "没有找到该教练信息");
            }

            gym.AddTrainer(trainer);
            await _gymsRepository.UpdateAsync(gym);

            return Result.Success;
            
        }
    }
}
